<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('code.dictionaryInfo')"
    custom-class="dialog-min-width"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formEdit" :rules="rules" label-width="120px">
      <el-row>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('code.name')" prop="name">
            <el-input v-model="formEdit.name" maxlength="128" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item>
            <template #label>
              {{ t("code.code") }}
              <el-popover
                placement="top"
                :width="200"
                effect="dark"
                trigger="click"
                :content="t('code.codeContent')"
              >
                <template #reference>
                  <el-icon style="vertical-align: sub; cursor: pointer"
                    ><Warning
                  /></el-icon>
                </template>
              </el-popover>
            </template>
            <template #default>
              <el-input v-model="formEdit.code" maxlength="64" clearable>
              </el-input
            ></template>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('code.value')">
            <el-input v-model="formEdit.value" maxlength="128" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('code.parentCode')">
            <el-cascader
              v-if="state.dialogFormVisible"
              :props="codeProps"
              show-all-levels
              clearable
              class="fix-el-cascader-width-100"
              v-model="formEdit.paths"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('code.extended')">
            <el-input v-model="formEdit.extended0" maxlength="128" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('code.extended')">
            <el-input v-model="formEdit.extended1" maxlength="128" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item prop="levelCode">
            <template #label>
              {{ t("code.levelCode") }}
              <el-popover
                placement="top"
                :width="200"
                effect="dark"
                trigger="click"
                :content="t('code.levelCodeContent')"
              >
                <template #reference>
                  <el-icon style="vertical-align: sub; cursor: pointer"
                    ><Warning
                  /></el-icon>
                </template>
              </el-popover>
            </template>
            <template #default>
              <el-input v-model="formEdit.levelCode" maxlength="64" clearable>
              </el-input
            ></template>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24"></el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('code.visible')">
            <el-switch
              v-model="formEdit.visible"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('code.description')" maxlength="64">
            <el-input v-model="formEdit.description" type="textarea">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { Warning } from "@element-plus/icons-vue";
import utils from "../../../utils/utils";
import apiCode from "../api/code";
import CodeTreeNode from "./tree-node";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
const formRef = ref();

const formEditOriginal = () => {
  return {
    codeId: "",
    parentId: "",
    levelCode: "",
    name: "",
    code: "",
    value: "",
    // 提交数据库，逗号分隔字符串
    path: "",
    // 前台临时使用，绑定下拉树
    paths: <any>null,
    extended0: "",
    extended1: "",
    visible: 1,
    description: "",
  };
};
const formEdit = reactive(formEditOriginal());

const rules = reactive({
  name: [
    { required: true, message: () => t("common.required"), trigger: "blur" },
  ],
  code: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  value: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],

  levelCode: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
});

const state = reactive({
  dialogFormVisible: false,
});

const emit = defineEmits<{
  (event: "on-submit-success", row: any): void;
}>();

const codeProps = {
  label: "name",
  value: "codeId",
  leaf: "leaf",
  checkStrictly: true,
  lazy: true,
  async lazyLoad(node: any, resolve: any) {
    if (node.level === 0) {
      let childs = await apiCode.loadChilds("0");
      let nodes = Array<CodeTreeNode>();
      Object.assign(nodes, childs);
      nodes.forEach((m: any) => {
        m.name = m.name + "-" + m.code;
      });
      return resolve(nodes);
    } else {
      if (node.data.leaf) {
        resolve([]);
      }
      let childs = await apiCode.loadChilds(node.data.codeId);
      let nodes = Array<CodeTreeNode>();
      Object.assign(nodes, childs);
      nodes.forEach((m: any) => {
        m.name = m.name + "-" + m.code;
      });
      return resolve(nodes);
    }
  },
};

const handleSubmit = async () => {
  await formRef.value.validate();

  formEdit.parentId = "";
  if (formEdit.paths != null && formEdit.paths.length > 0) {
    formEdit.parentId = formEdit.paths[formEdit.paths.length - 1];
    formEdit.path = formEdit.paths.join(",");
  } else {
    formEdit.parentId = "";
    formEdit.path = "";
  }

  apiCode
    .updateCode(formEdit)
    .then((response: any) => {
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = (row: any) => {
  // console.log(row);
  Object.assign(formEdit, formEditOriginal());
  if (row != undefined) {
    apiCode
      .getCode(row.codeId)
      .then((response: any) => {
        if (response.data.code == 200) {
          Object.assign(formEdit, response.data.data);
          if (formEdit.paths.length > 0) {
            formEdit.paths = formEdit.path.split(",");
          }
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  }
  state.dialogFormVisible = true;
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

defineExpose({
  show,
});
</script>
